const path = require('path')
const glob = require('glob')
const { sep } = path

module.exports = (app) => {
  // 读取middleware目录下的所有中间件
  const middlewarePath = path.resolve(app.businessPath, `.${sep}middleware`)
  const fileList = glob.sync(
    path.resolve(middlewarePath, `.${sep}**${sep}**.js`)
  )
  console.log(sep, fileList)
  const middleware = {}
  fileList.forEach((itemPath) => {
    const filePath = path.resolve(itemPath)
    let name = filePath.split(`middleware${sep}`).pop() || ''
    name = name.replace(/[_-][a-z]/gi, (s) => s.substring(1).toUpperCase())
    const paths = name.split(sep)
    const len = paths.length
    // 读取中间件key,约定中间件为 middleware/name/name1/index.js的形式,key为name-name1...
    if (len > 1 && paths.at(-1) === 'index.js') {
      let temMiddleware = middleware
      paths.slice(0, -1).forEach((v, k) => {
        if (k === len - 2) {
          console.log(filePath, v)
          temMiddleware[v] = require(filePath)(app)
        } else {
          if (!temMiddleware?.[v]) {
            temMiddleware[v] = {}
          }
          temMiddleware = temMiddleware[v]
        }
      })
    }
  })
  console.log(middleware)
  console.log(middleware.a.b())
  app.middleware = middleware
}
